package safeCommitter.test.executor;

import java.util.LinkedList;
import java.util.List;

import org.testng.xml.XmlSuite;

import safeCommitter.model.TestType;
import safeCommitter.test.executor.builder.SCTestBuilder;
import safeCommitter.test.executor.builder.SCXmlSuiteBuilder;
import safeCommitter.test.executor.junit.JunitExecutor;
import safeCommitter.test.executor.launcher.internal.SCTestArgsBuilder;
import safeCommitter.test.executor.launcher.socket.SCTestSocketWriter;
import safeCommitter.test.executor.testNG.TestNGExecutor;
import safeCommitter.test.report.SCReport;

public class SCTestExecutor implements ISCTestExecutor {

	JunitExecutor junitExecutor = new JunitExecutor();

	public void executeAllTests(final String[] args) {
		String[] testsFoundFromSearch = SCTestArgsBuilder
				.getTestsFromSearch(args[0]);
		SCTestSocketWriter socketWriter = new SCTestSocketWriter(Integer
				.parseInt(args[1]));
		try {
			executeBody(args, testsFoundFromSearch, socketWriter);
		} finally {
			socketWriter.write("END");
			socketWriter.closeClientSocket();
		}
	}

	private void executeBody(final String[] args,
			final String[] testsFoundFromSearch,
			final SCTestSocketWriter socketWriter) {
		List<XmlSuite> suitesFromFiles = getSuitesFromFiles(args);
		if (args.length == 0 && suitesFromFiles.size() == 0) {
			socketWriter.write("NOTESTS");
		} else {
			SCTestBuilder builder = new SCTestBuilder(testsFoundFromSearch);
			TestNGExecutor testNGExecutor = new TestNGExecutor(socketWriter);
			testNGExecutor.executeFromFileAndClass(suitesFromFiles, builder
					.getTestNGClasses());

			SCReport junitReport = junitExecutor.execJunit(builder
					.getJunitTests(), socketWriter);
			socketWriter.write("COUNT:" + TestType.JUNIT.name() + ":"
					+ junitReport.getTestCount());
		}
	}

	private List<XmlSuite> getSuitesFromFiles(final String[] filePaths) {
		if (filePaths.length < 3 || filePaths[2] == null
				|| filePaths[2].equals("")
				|| "true".equalsIgnoreCase(filePaths[0])) {
			return new LinkedList<XmlSuite>();
		}
		SCXmlSuiteBuilder builder = new SCXmlSuiteBuilder();
		List<XmlSuite> xmlSuite = builder.getXmlSuitesFromFiles(filePaths[2]);
		return xmlSuite;

	}

	public static void main(final String[] args) {
		new SCTestExecutor().executeAllTests(args);
	}

}
